package com.watchmen.wechat.util;

import java.security.MessageDigest;
import java.util.Map;
import java.util.SortedMap;

import org.springframework.stereotype.Component;



/**
 * @author kk
 * @Description MD5 加密工具
 */
@Component
public class MD5Util {
	
	private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
								"6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

	
	
	/**
	 * MD5加密
	 * @param origin 要加密的字符串
	 * @param charsetname 字符编码
	 * @return
	 */
	public String MD5Encode (String origin, String charsetname){
		 String result = "";
		
		 try {
			 result = origin;
			 MessageDigest md = MessageDigest.getInstance("MD5");
			
			 if(null == charsetname || "".equals(charsetname)){
				 result = this.byteArrayToHexString(md.digest(result.getBytes()));
			 }else{
				 result = byteArrayToHexString(md.digest(result.getBytes(charsetname)));
			 }
			 
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	
	/**
	 * @param byte数组转换字符串
	 * @return 
	 */
	private static String byteArrayToHexString(byte b[]) {
	    StringBuffer resultSb = new StringBuffer();
	    for (int i = 0; i < b.length; i++)
	        resultSb.append(byteToHexString(b[i]));
	    return resultSb.toString();
	 }
	
	
	
	 private static String byteToHexString(byte b) {
	        int n = b;
	        if (n < 0)
	            n += 256;
	        int d1 = n / 16;
	        int d2 = n % 16;
	        return hexDigits[d1] + hexDigits[d2];
	 }
	 
	
	/**
	 * @param characterEncoding 字符编码
	 * @param params 加密参数
	 * @param key 加密所用的秘钥
	 * @return
	 */
	public String createSign(String characterEncoding,SortedMap<String, Object> params,String key){
		StringBuffer sb = new StringBuffer();
		params.forEach((k,v)->{
			if(null != v && 
			   !"".equals(v) && 
			   !"sign".equals(k) && 
			   !"key".equals(k)){
				sb.append(k + "=" + v + "&"); 
			}
		});
		sb.append("key=" + key);
		String sign = this.MD5Encode(sb.toString(), characterEncoding).toUpperCase(); 
		return sign;
	}
	
	
	
	
}
